/*
Copyright [2023] [fuwen_soft]
*/
package vip.xiaonuo.modular.xyethnic.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.lang.tree.Tree;
import cn.hutool.core.lang.tree.TreeNodeConfig;
import cn.hutool.core.lang.tree.TreeUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.spring.SpringUtil;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import org.springframework.beans.factory.annotation.Autowired;
import vip.xiaonuo.core.consts.CommonConstant;
import vip.xiaonuo.core.context.login.LoginContextHolder;
import vip.xiaonuo.core.enums.CommonStatusEnum;
import vip.xiaonuo.core.exception.ServiceException;
import vip.xiaonuo.core.factory.PageFactory;
import vip.xiaonuo.core.pojo.page.PageResult;
import vip.xiaonuo.core.util.PoiUtil;
import vip.xiaonuo.modular.xyethnic.entity.XyEthnic;
import vip.xiaonuo.modular.xyethnic.enums.XyEthnicExceptionEnum;
import vip.xiaonuo.modular.xyethnic.form.*;
import vip.xiaonuo.modular.xyethnic.mapper.XyEthnicMapper;
import vip.xiaonuo.modular.xyethnic.param.XyEthnicParam;
import vip.xiaonuo.modular.xyethnic.service.XyEthnicService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import vip.xiaonuo.modular.xyethnic.vo.*;
import vip.xiaonuo.modular.xyethniccate.entity.XyEthnicCate;
import vip.xiaonuo.modular.xyethniccate.service.XyEthnicCateService;
import vip.xiaonuo.modular.xylogy.entity.XyLogy;
import vip.xiaonuo.modular.xylogy.service.XyLogyService;
import vip.xiaonuo.modular.xylogyauth.entity.XyLogyAuth;
import vip.xiaonuo.modular.xylogyauth.service.XyLogyAuthService;
import vip.xiaonuo.modular.xylogylogs.service.XyLogyLogsService;
import vip.xiaonuo.modular.xyuser.entity.XyUser;
import vip.xiaonuo.modular.xyuser.service.XyUserService;

import javax.annotation.Resource;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

import static vip.xiaonuo.modular.xyethnic.constant.EthnicConstant.BindFlagConstant.*;
import static vip.xiaonuo.modular.xyethnic.constant.EthnicConstant.ExistUserConstant.EXIST_YES;
import static vip.xiaonuo.modular.xyethnic.constant.EthnicConstant.OldDataConstant.NEW_DATA;
import static vip.xiaonuo.modular.xyethnic.constant.EthnicConstant.OldDataConstant.OLD_DATA;
import static vip.xiaonuo.modular.xyethnic.constant.EthnicConstant.RelationshipConstant.*;
import static vip.xiaonuo.modular.xyethnic.constant.EthnicConstant.SexConstant.MAN_SEX;
import static vip.xiaonuo.modular.xyethnic.constant.EthnicConstant.SexConstant.WOMAN;
import static vip.xiaonuo.modular.xylogy.enums.XyLogyAuthEnum.*;

/**
 * 族员service接口实现类
 *
 * @author yanwei
 * @date 2023-05-05 15:44:28
 */
@Service
public class XyEthnicServiceImpl extends ServiceImpl<XyEthnicMapper, XyEthnic> implements XyEthnicService {

    @Autowired
    private XyLogyAuthService xyLogyAuthService;

    @Resource
    private XyEthnicMapper xyEthnicMapper;

    @Autowired
    private XyLogyLogsService logyLogsService;

    @Autowired
    private XyEthnicCateService xyEthnicCateService;

    @Override
    public PageResult<XyEthnic> page(XyEthnicParam xyEthnicParam) {
        QueryWrapper<XyEthnic> queryWrapper = new QueryWrapper<>();
        if (ObjectUtil.isNotNull(xyEthnicParam)) {

            // 根据关联的族谱编号 查询
            if (ObjectUtil.isNotEmpty(xyEthnicParam.getLogyId())) {
                queryWrapper.lambda().eq(XyEthnic::getLogyId, xyEthnicParam.getLogyId());
            }
            // 根据姓氏 查询
            if (ObjectUtil.isNotEmpty(xyEthnicParam.getSurname())) {
                queryWrapper.lambda().eq(XyEthnic::getSurname, xyEthnicParam.getSurname());
            }
            // 根据名字 查询
            if (ObjectUtil.isNotEmpty(xyEthnicParam.getName())) {
                queryWrapper.lambda().eq(XyEthnic::getName, xyEthnicParam.getName());
            }
            // 根据常用名 查询
            if (ObjectUtil.isNotEmpty(xyEthnicParam.getCommName())) {
                queryWrapper.lambda().eq(XyEthnic::getCommName, xyEthnicParam.getCommName());
            }
            // 根据排序，垂直排序 查询
            if (ObjectUtil.isNotEmpty(xyEthnicParam.getSortList())) {
                queryWrapper.lambda().eq(XyEthnic::getSortList, xyEthnicParam.getSortList());
            }
            // 根据关系 查询
            if (ObjectUtil.isNotEmpty(xyEthnicParam.getRelationship())) {
                queryWrapper.lambda().eq(XyEthnic::getRelationship, xyEthnicParam.getRelationship());
            }
            // 根据真实关系，例如，兄妹,妻等。转义或的词条头衔 查询
            if (ObjectUtil.isNotEmpty(xyEthnicParam.getRealRelationship())) {
                queryWrapper.lambda().eq(XyEthnic::getRealRelationship, xyEthnicParam.getRealRelationship());
            }
            // 根据性别,2=女，1=男 查询
            if (ObjectUtil.isNotEmpty(xyEthnicParam.getGenderSex())) {
                queryWrapper.lambda().eq(XyEthnic::getGenderSex, xyEthnicParam.getGenderSex());
            }
            // 根据排行 查询
            if (ObjectUtil.isNotEmpty(xyEthnicParam.getLogySort())) {
                queryWrapper.lambda().eq(XyEthnic::getLogySort, xyEthnicParam.getLogySort());
            }
            // 根据出生日期(农历) 查询
            if (ObjectUtil.isNotEmpty(xyEthnicParam.getNewDate())) {
                queryWrapper.lambda().eq(XyEthnic::getNewDate, xyEthnicParam.getNewDate());
            }
            // 根据1=公开，2=隐藏，出生日期隐藏 查询
            if (ObjectUtil.isNotEmpty(xyEthnicParam.getNewDatePri())) {
                queryWrapper.lambda().eq(XyEthnic::getNewDatePri, xyEthnicParam.getNewDatePri());
            }
            // 根据用户是否在世,1=在世,2=不在世 查询
            if (ObjectUtil.isNotEmpty(xyEthnicParam.getExistUser())) {
                queryWrapper.lambda().eq(XyEthnic::getExistUser, xyEthnicParam.getExistUser());
            }
            // 根据绑定的用户,如果为null,可以邀请绑定，否则不可以 查询
            if (ObjectUtil.isNotEmpty(xyEthnicParam.getUserId())) {
                queryWrapper.lambda().eq(XyEthnic::getUserId, xyEthnicParam.getUserId());
            }
            // 根据绑定审核 0=无需审核,1=未审核，2=已审核，审核失败 查询
//            if (ObjectUtil.isNotEmpty(xyEthnicParam.getBindFlag())) {
//                queryWrapper.lambda().eq(XyEthnic::getBindFlag, xyEthnicParam.getBindFlag());
//            }
            // 特殊绑定
            if (Integer.valueOf(-1).equals(xyEthnicParam.getBindFlag())){
                queryWrapper.lambda().in(XyEthnic::getBindFlag, NOT_PRO,OK_PRO,FAIL_PRO);
            }else{
                queryWrapper.lambda().eq(Objects.nonNull(xyEthnicParam.getBindFlag()),XyEthnic::getBindFlag, xyEthnicParam.getBindFlag());

            }
            // 根据修改审核 0=无需审核,1=未审核，2=已审核，审核失败 查询
            if (ObjectUtil.isNotEmpty(xyEthnicParam.getChageFlag())) {
                queryWrapper.lambda().eq(XyEthnic::getChageFlag, xyEthnicParam.getChageFlag());
            }
            // 根据层级，多少代 查询
            if (ObjectUtil.isNotEmpty(xyEthnicParam.getLevels())) {
                queryWrapper.lambda().eq(XyEthnic::getLevels, xyEthnicParam.getLevels());
            }
            // 根据族父编号，默认为1始祖世 查询
            if (ObjectUtil.isNotEmpty(xyEthnicParam.getParentId())) {
                queryWrapper.lambda().eq(XyEthnic::getParentId, xyEthnicParam.getParentId());
            }
              // 这个 特殊
            if (ObjectUtil.isNotEmpty(xyEthnicParam.getOldDataId())) {
                queryWrapper.lambda().eq(XyEthnic::getOldDataId, xyEthnicParam.getOldDataId());
            }else{
                queryWrapper.lambda().isNotNull(XyEthnic::getOldDataId);

            }
            queryWrapper.lambda().orderByDesc(XyEthnic::getCreateTime);

        }
        return new PageResult<>(this.page(PageFactory.defaultPage(), queryWrapper));
    }

    @Override
    public List<XyEthnic> list(XyEthnicParam xyEthnicParam) {
        return this.list();
    }

    @Override
    public void add(XyEthnicParam xyEthnicParam) {
        XyEthnic xyEthnic = new XyEthnic();
        BeanUtil.copyProperties(xyEthnicParam, xyEthnic);
        this.save(xyEthnic);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void delete(List<XyEthnicParam> xyEthnicParamList) {
        xyEthnicParamList.forEach(xyEthnicParam -> {
            this.removeById(xyEthnicParam.getId());
        });
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void edit(XyEthnicParam xyEthnicParam) {
        XyEthnic xyEthnic = this.queryXyEthnic(xyEthnicParam);
        BeanUtil.copyProperties(xyEthnicParam, xyEthnic);
        this.updateById(xyEthnic);
    }

    @Override
    public XyEthnic detail(XyEthnicParam xyEthnicParam) {
        return this.queryXyEthnic(xyEthnicParam);
    }

    /**
     * 获取族员
     *
     * @author yanwei
     * @date 2023-05-05 15:44:28
     */
    private XyEthnic queryXyEthnic(XyEthnicParam xyEthnicParam) {
        XyEthnic xyEthnic = this.getById(xyEthnicParam.getId());
        if (ObjectUtil.isNull(xyEthnic)) {
            throw new ServiceException(XyEthnicExceptionEnum.NOT_EXIST);
        }
        return xyEthnic;
    }

    @Override
    public void export(XyEthnicParam xyEthnicParam) {
        List<XyEthnic> list = this.list(xyEthnicParam);
        PoiUtil.exportExcelWithStream("SnowyXyEthnic.xls", XyEthnic.class, list);
    }

    /**
     * 初始化始组
     * @param xyLogy
     * @param userId
     */
    @Override
    public void initSource(XyLogy xyLogy, String userId) {
        XyUserService xyUserService = SpringUtil.getBean(XyUserService.class);
        XyEthnic xyEthnic = new XyEthnic();
        xyEthnic.setBindFlag(NON_PRO);
        xyEthnic.setLevels(1);
        xyEthnic.setLogyId(xyLogy.getId());
        xyEthnic.setGenderSex(MAN_SEX);
        xyEthnic.setRelationship("1");
        xyEthnic.setNewDatePri(1L);
        xyEthnic.setNewDate(DateUtil.format(new Date(),"yyyy-MM-dd"));
        xyEthnic.setSortList(1L);
        xyEthnic.setCommName(xyUserService.getById(userId).getNickName());
        xyEthnic.setSurname(xyLogy.getSurname());
        xyEthnic.setParentId("1");
        save(xyEthnic);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveEthnic(EthnicForm ethnicForm, String userId) {
        XyEthnic thisEthnic = getById(ethnicForm.getCronId());

        beforeCheck(thisEthnic,ethnicForm,userId);

        /**
         * 判断当前用户身份属于什么呢。
         */
        swtich(thisEthnic,userId,ethnicForm);

    }

    @Override
    public void chageEthnic(EthnicEditForm ethnicEditForm, String userId) {
        // 查看当前权限问题
        Boolean flag = authParms(userId, ethnicEditForm);
        XyEthnic xyEthnic = getById(ethnicEditForm.getId());
        BeanUtil.copyProperties(ethnicEditForm,xyEthnic);
        if (flag){
            logyLogsService.saveLogyLog(userId,ethnicEditForm.getLogyId(),StrUtil.format("当前族谱修改了族员,{}",ethnicEditForm.getName()));
            updateById(xyEthnic);
        }else{
            // 如果是协作者的就需要 总管理去审核了
            // 新建一个，设定下值 进行审核好了
            xyEthnic.setId(null);
            xyEthnic.setChageFlag(NOT_PRO);
            xyEthnic.setOldDataId(ethnicEditForm.getId());
            // 判定当前用户的审核查询
            save(xyEthnic);
        }

    }

    @Override
    public CountLogyVo countLogy(String id) {
        List<XyEthnic> xyEthnicList = list(Wrappers.<XyEthnic>lambdaQuery().isNull(XyEthnic::getOldDataId).eq(XyEthnic::getLogyId, id));
        // 红丁
        long redCount = xyEthnicList.stream().filter(item -> MAN_SEX.equals(item.getGenderSex()) && EXIST_YES.equals(item.getExistUser())).count();

        // 男丁
        long manCount = xyEthnicList.stream().filter(item -> MAN_SEX.equals(item.getGenderSex())).count();

        // 女丁
        long womanCount = xyEthnicList.stream().filter(item -> WOMAN.equals(item.getGenderSex()) && StrUtil.isBlank(item.getIsJoin())).count();

        // 始祖
        XyEthnic xyEthnic = xyEthnicList.stream().filter(item -> Integer.valueOf(1).equals(item.getLevels()) && "1".equals(item.getParentId()) && MAN_SEX.equals(item.getGenderSex())).findAny().orElseGet(XyEthnic::new);

        // 谱员

        CountLogyVo countLogyVo = new CountLogyVo();
        countLogyVo.setRedCount(redCount);
        countLogyVo.setManCount(manCount);
        countLogyVo.setWomanCount(womanCount);
        countLogyVo.setLogySourceName(StrUtil.blankToDefault(xyEthnic.getName(),xyEthnic.getCommName()));
        countLogyVo.setLogyCount(xyLogyAuthService.count(Wrappers.<XyLogyAuth>lambdaQuery().eq(XyLogyAuth::getLogyId,id)));
        return countLogyVo;
    }

    @Override
    public List<XyLogy> thisUserLogy() {
        XyLogyService xyLogyService = SpringUtil.getBean(XyLogyService.class);
        String userId = LoginContextHolder.me().getSysLoginUser().getStrId();
        List<XyLogyAuth> xyLogyAuths = xyLogyAuthService.list(Wrappers.<XyLogyAuth>lambdaQuery().select(XyLogyAuth::getLogyId).eq(XyLogyAuth::getDisabled,1).eq(XyLogyAuth::getUserId, userId));
        Set<String> logyIds = xyLogyAuths.stream().map(XyLogyAuth::getLogyId).collect(Collectors.toSet());
        return  logyIds.isEmpty() ? Lists.newArrayList() : xyLogyService.listByIds(logyIds);
    }

    @Override
    public List<LevelsLogyVo> logyLevels(EthnicTreeListForm ethnicTreeListForm, String userId) {
        String logyId = ethnicTreeListForm.getLogyId();
        String formDict = ethnicTreeListForm.getFormDict();
        LinkedList<LevelsLogyVo> levelsLogyVos = Lists.newLinkedList();
        // 查看当前会员的权限信息
       // String perMisc = getPerMisc(logyId, userId);
        doEthnicPoint(logyId,1,levelsLogyVos,formDict,true);
        // 查询所有族员信息
//        if (ALL_AUTH.getAuthP().equals(perMisc)) {
//            // 全部权限,全部查询
//
//        }else{
//            // 不是全部权限，查询对应权限，最高的等级
//            String[] logyIds = perMisc.split(",");
//            List<XyEthnic> xyEthnics = listByIds(Arrays.asList(logyIds));
//            // 查询里面等级最低的
//            //Arrays.sort(xyEthnics,(oldData,newData)-> oldData.);
//            XyEthnic minEthnic = xyEthnics.stream().min(Comparator.comparing(XyEthnic::getLevels)).get();
//            // 以这个为基准开始往下延申就可以了.
//            doEthnicPoint(logyId,minEthnic.getLevels(),levelsLogyVos,formDict,true);
//        }



        return levelsLogyVos;
    }

    private String getPerMisc(String logyId, String userId) {
        XyLogyAuth logyAuth = xyLogyAuthService.getOne(Wrappers.<XyLogyAuth>lambdaQuery().eq(XyLogyAuth::getDisabled, 1).eq(XyLogyAuth::getLogyId, logyId).eq(XyLogyAuth::getUserId, userId));
        return logyAuth.getPerMisc();
    }

    /**
     * 根据树形结构查询
     * @param ethnicTreeListForm
     * @param userId
     */
    @Override
    public TreeLogyVo treeListData(EthnicTreeListForm ethnicTreeListForm, String userId) {
        String logyId = ethnicTreeListForm.getLogyId();
        String formDict = ethnicTreeListForm.getFormDict();
        TreeLogyVo treeLogyVo = null;
     //   String perMisc = getPerMisc(logyId, userId);
//        if (ALL_AUTH.getAuthP().equals(perMisc)) {
//            // 全部作为树形
//        }else{
//            // 其中一部分才是
//            String[] ethnicIds = perMisc.split(",");
//            List<XyEthnic> childEthnics = listByIds(Arrays.asList(ethnicIds));
//            // 拿出最小的等级
//            XyEthnic minEthnic = childEthnics.stream().min(Comparator.comparing(XyEthnic::getLevels)).get();
//           // 开始获取吧
//            treeLogyVo =   doTreeChildPoint(minEthnic.getLevels(),logyId,formDict,true);
//        }
        treeLogyVo =   doTreeChildPoint(1,logyId,formDict,true);

        return treeLogyVo;

    }

    /**
     * 查询行传列表
     * @param logyId
     * @return
     */
    @Override
    public List<LineLevelsLogyVo> lineChildList(String logyId) {
        List<LineLevelsLogyVo> lineLevelsLogyVos = Lists.newArrayList();
        // 行转该怎么去做呢？
        List<XyEthnic> xyEthnics = xyEthnicList(logyId,null,null);
        // 分层组合
        // 数据结构为，每一世的 都是一行结构，每一世的都是 主系，主系N配偶即可
        // 这是主关系
        Map<Integer, List<XyEthnic>> levelByEthnicList = xyEthnics.stream().collect(Collectors.groupingBy(XyEthnic::getLevels));
        levelByEthnicList.forEach((key,val) ->{
            LineLevelsLogyVo lineLevelsLogyVo = new LineLevelsLogyVo();

            lineLevelsLogyVo.setLevel(key);
            // 主关系确定
            List<XyEthnic> fuEthnicList = val.stream().filter(item -> StrUtil.isBlank(item.getIsJoin())).collect(Collectors.toList());
            lineLevelsLogyVo.setListEthnicVos(
                    getListEthnicVoList(val, fuEthnicList)
            );
            lineLevelsLogyVos.add(lineLevelsLogyVo);
        });
     //排序下
        return lineLevelsLogyVos.stream().sorted(Comparator.comparing(LineLevelsLogyVo::getLevel)).collect(Collectors.toList());
    }

    /**
     * 当前用户是否有绝对的权力去审核
     * @param authEditEthnicForm
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void authEditChange(AuthEditEthnicForm authEditEthnicForm) {
        String userId = LoginContextHolder.me().getSysLoginUser().getStrId();
        XyEthnic xyEthnic = getOne(Wrappers.<XyEthnic>lambdaQuery().eq(XyEthnic::getId,authEditEthnicForm.getId()).isNotNull(XyEthnic::getOldDataId));
        Integer chageFlag = xyEthnic.getChageFlag();
        Assert.isTrue(Objects.nonNull(xyEthnic),"当前数据已被审核!");
        String perMisc = getPerMisc(xyEthnic.getLogyId(), userId);
        Assert.isTrue(ALL_AUTH.getAuthP().equals(perMisc),"暂无权限!");
        // 可以了，判定状态吧，如果审核成功的话，那就把当前数据 copy 到最新数据上
        xyEthnic.setChageFlag(authEditEthnicForm.getChageFlag());
        updateById(xyEthnic);
        if (OK_PRO.equals(authEditEthnicForm.getChageFlag())  && (!OK_PRO.equals(chageFlag))){
            // 审核成功了
            logyLogsService.saveLogyLog(userId,xyEthnic.getLogyId(),StrUtil.format("协作者修改了族员信息:{}",xyEthnic.getName()));
            XyEthnic newXyEthnic = getById(xyEthnic.getOldDataId());
            BeanUtil.copyProperties(xyEthnic,newXyEthnic,"chageFlag","oldDataId","id");
            updateById(newXyEthnic);
        }



    }


    /**
     * 绑定对应的用户信息
     * @param ethnicId
     */
    @Override
    public void pleaseBindEthnic(String ethnicId) {
        String userId = LoginContextHolder.me().getSysLoginUser().getStrId();
        XyUserService xyUserService = SpringUtil.getBean(XyUserService.class);
        XyLogyService xyLogyService = SpringUtil.getBean(XyLogyService.class);

        XyUser xyUser = xyUserService.getById(userId);
        XyEthnic xyEthnic = getById(ethnicId);
        Assert.isTrue(xyLogyAuthService.count(Wrappers.<XyLogyAuth>lambdaQuery().eq(XyLogyAuth::getUserId,userId).eq(XyLogyAuth::getLogyId,xyEthnic.getLogyId()))<=0,"您已有绑定,请核实!");
        // 没有的话就 可以保存
        //TODO 这块需要重新对接
        xyEthnic.setBindFlag(NOT_PRO);
        xyEthnic.setUserId(userId);
        updateById(xyEthnic);
        // 绑定成功后，给当前用户新增这个家谱 并且赋予权限。
        XyLogy xyLogy = xyLogyService.getById(xyEthnic.getLogyId());
        // 初始化族谱权限
        xyLogyAuthService.save(new XyLogyAuth(ALL_PUTONG_AUTH,userId,xyUser.getPhoneNumber(),xyLogy.getId(),1));
    }

    @Override
    public void bindEthnicChange(AuthEditEthnicsForm authEditEthnicForm) {
        String userId = LoginContextHolder.me().getSysLoginUser().getStrId();
        XyEthnic xyEthnic = getById(authEditEthnicForm.getId());
        String perMisc = getPerMisc(xyEthnic.getLogyId(), userId);
        Assert.isTrue(ALL_AUTH.getAuthP().equals(perMisc),"暂无权限!");
        xyEthnic.setBindFlag(authEditEthnicForm.getBindFlag());
        updateById(xyEthnic);
        // 开始绑定
        // 开始记录
        if (OK_PRO.equals(authEditEthnicForm.getBindFlag()) && (!OK_PRO.equals(xyEthnic.getBindFlag()))) {
            // 审核成功记录日志
            logyLogsService.saveLogyLog(userId,xyEthnic.getLogyId(),StrUtil.format("管理员同意了族员绑定:{}",xyEthnic.getName()));
           // 初始化权限
            String userId1 = xyEthnic.getUserId();
            XyUserService xyUserService = SpringUtil.getBean(XyUserService.class);
            XyLogyService xyLogyService = SpringUtil.getBean(XyLogyService.class);

            XyUser xyUser = xyUserService.getById(userId1);
            // 绑定成功后，给当前用户新增这个家谱 并且赋予权限。
            XyLogy xyLogy = xyLogyService.getById(xyEthnic.getLogyId());
            // 初始化族谱权限
            xyLogyAuthService.save(new XyLogyAuth(ALL_PUTONG_AUTH,userId1,xyUser.getPhoneNumber(),xyLogy.getId(),1));
            // 然后呢？记录对应用户的日志呗。
            saveAuthEthnic(xyEthnic);
        }


    }

    @Override
    public List<JSONObject> pdfOpenLineChildList(String logyId) {

        return null;
    }

    @Override
    public List<ListEthnicVo> lineChildListOld(String logyId) {
        // 查询这个家族的始祖
        XyEthnic one = getOne(Wrappers.<XyEthnic>lambdaQuery().eq(XyEthnic::getLogyId,logyId).eq(XyEthnic::getLevels, 1).eq(XyEthnic::getParentId, "1").eq(XyEthnic::getRelationship, father));
       // getOne(Wrappers.<XyEthnic>lambdaQuery().eq(XyEthnic::getLevels,1).eq(XyEthnic::getParentId,"1").eq(XyEthnic::getRelationship,father));
        LinkedList<ListEthnicVo> objects = Lists.newLinkedList();
        List<LineLevelsLogyVo> lineLevelsLogyVos = lineChildList(logyId);
        for (LineLevelsLogyVo lineLevelsLogyVo : lineLevelsLogyVos) {
            List<ListEthnicVo> listEthnicVos = lineLevelsLogyVo.getListEthnicVos();
            for (ListEthnicVo listEthnicVo : listEthnicVos) {
                XyEthnic xyEthnic = getById(listEthnicVo.getId());
                JSONObject dataJson2 = new JSONObject();
                dataJson2.put("orgName",StrUtil.format("始祖:{}",StrUtil.blankToDefault(one.getName(),"未知")));
                dataJson2.put("name", StrUtil.blankToDefault(listEthnicVo.getName(),"未知"));
                dataJson2.put("broThDate",StrUtil.format("生庚{}","请选择".equals(xyEthnic.getNewDate()) ? "未详": StrUtil.emptyToDefault(xyEthnic.getNewDate(),"未详")));
                dataJson2.put("existUser",Long.valueOf(2).equals(xyEthnic.getExistUser()) ? "不在世" : "在世");
                dataJson2.put("ethnicInfos",StrUtil.blankToDefault(xyEthnic.getEthnicInfo(),""));
                listEthnicVo.setDictFrom(StrUtil.join(";",dataJson2.values()));
                objects.addLast(listEthnicVo);
            }
        }
        return objects;
    }

    @Override
    public List<Tree<Object>>  treeListDataTree(EthnicTreeListForm ethnicTreeListForm, String userId) {
        String logyId = ethnicTreeListForm.getLogyId();
        String formDict = ethnicTreeListForm.getFormDict();
        // 查询主枝干

        List<XyEthnic> xyEthnics = xyEthnicList(logyId, formDict, null);
        TreeNodeConfig config = new TreeNodeConfig();
        config.setParentIdKey("parentId");
        // 过滤下主分干
        List<XyEthnic> collect = xyEthnics.parallelStream().filter(item -> StrUtil.isBlank(item.getIsJoin())).sorted(Comparator.comparing(XyEthnic::getSortList)).collect(Collectors.toList());
        return TreeUtil.build(collect, "1", config, (object, tree) -> {
            tree.setId(object.getId());//必填属性.
            tree.setParentId(object.getParentId());//必填属性
            String format = StrUtil.format("{} {}",StrUtil.blankToDefault(object.getSurname(),"未知"), StrUtil.blankToDefault(object.getName(),"未知"));
            tree.setName(format);
            tree.putExtra("realData",object);
            // 是否是始祖？
            if ("1".equals(object.getParentId())){
                tree.putExtra("sugender","始祖");
            }else{
                String joinName = object.getLogySoftName();
                if (StrUtil.isNotBlank(joinName)) {
                    tree.putExtra("sugender",joinName);
                }else{
                    XyEthnicCate xyEthnicCate = xyEthnicCateService.getById(object.getLogySort());
                    if (ObjectUtil.isNotEmpty(xyEthnicCate)){
                        tree.putExtra("sugender",xyEthnicCate.getJoinName());
                    }else{
                        tree.putExtra("sugender","暂无");
                    }

                }

            }

            tree.putExtra("level",object.getLevels());
            tree.putExtra("label",format);
            tree.putExtra("bindXyEthnics",xyEthnics.stream().filter(item -> object.getId().equals(item.getIsJoin())).map(item2 -> {
                ListEthnicVo listEthnicVo2 = new ListEthnicVo();
                BeanUtil.copyProperties(item2, listEthnicVo2);
                return listEthnicVo2;
            }).sorted(Comparator.comparing(ListEthnicVo::getSortList)).collect(Collectors.toList()));
            // 绑定下妻子得信息
            //tree.setWeight(object.getIndex());//更新一波,weight为排序字段,不过测试时子级好像并没有生效

            // 扩展属性 ...
            //tree.putExtra("children",object.getChildren());
        });
    }

    @Override
    public void chagePoiEthnic(Integer poi, String id) {
        XyEthnic xyEthnic = getById(id);
        // 这货是个主分支吗
        String relationship = xyEthnic.getRelationship();
        Assert.isTrue(allMoveLevel.contains(relationship),"移动失败,只限于主枝移动!");
        // 开始移动
        // 查找当前级别得等级
        List<XyEthnic> xyEthnicList = list(Wrappers.<XyEthnic>lambdaQuery().eq(XyEthnic::getLogyId, xyEthnic.getLogyId()).eq(XyEthnic::getLevels, xyEthnic.getLevels()).in(XyEthnic::getRelationship, allMoveLevel).orderByAsc(XyEthnic::getSortList));
        int i = 0;
       forLab: for (XyEthnic ethnic : xyEthnicList) {
            // 查找当前自己最近得人
            if (ethnic.getId().equals(xyEthnic.getId())){
                if (Integer.valueOf(1).equals(poi)){
                    // 左边

                        // 可以位置互换了
                        Long sortList = xyEthnic.getSortList();
                        XyEthnic xyEthnic1 = xyEthnicList.get(i - 1);
                        xyEthnic.setSortList( xyEthnic1.getSortList());
                        xyEthnic1.setSortList(sortList);
                        break forLab;

                }else{

                        Long sortList = xyEthnic.getSortList();
                        XyEthnic xyEthnic1 = xyEthnicList.get(i + 1);
                        xyEthnic.setSortList( xyEthnic1.getSortList());
                        xyEthnic1.setSortList(sortList);
                        break forLab;

                    // 右边
                }
            }
            i++;
        }

        // 然后根据这个 排序查找同族谱，同级别的 主分支看看有没有排序，有的话就更改下，没有就假执行即可。
//        List<XyEthnic> xyEthnicList = list(Wrappers.<XyEthnic>lambdaQuery().eq(XyEthnic::getSortList,sortList).eq(XyEthnic::getLogyId, xyEthnic.getLogyId()).eq(XyEthnic::getLevels, xyEthnic.getLevels()).in(XyEthnic::getRelationship, allMoveLevel));
//        if (!xyEthnicList.isEmpty()){
//            for (XyEthnic ethnic : xyEthnicList) {
//                if (Integer.valueOf(1).equals(poi)){
//                    ethnic.setSortList(ethnic.getSortList()+1);
//                }else{
//                    ethnic.setSortList(ethnic.getSortList()-1);
//                }
//                ethnic.setSortList(ethnic.getSortList());
//            }
//            updateBatchById(xyEthnicList);
//        }else{
//            sortList = xyEthnic.getSortList();
//        }
        updateBatchById(xyEthnicList);
        updateById(xyEthnic);

    }

    @Override
    public List<DictLevelStrVo> findLevelsSelect(String id) {
        XyEthnic xyEthnic = getById(id);
        List<DictLevelStrVo> dictLevelStrVos = Lists.newArrayList();
        // 当前族员向上排的族员信息
        List<XyEthnic> xyEthnicList = list(Wrappers.<XyEthnic>lambdaQuery().eq(XyEthnic::getLogyId, xyEthnic.getLogyId()).lt(XyEthnic::getLevels, xyEthnic.getLevels()).orderByAsc(XyEthnic::getLevels));
        for (XyEthnic ethnic : xyEthnicList) {
            DictLevelStrVo dictLevelStrVo = new DictLevelStrVo();
            dictLevelStrVo.setLevels(ethnic.getLevels());
            dictLevelStrVo.setId(ethnic.getId());
            dictLevelStrVo.setDictFormStr(StrUtil.format("第{}世:{}",ethnic.getLevels(),ethnic.getName()));
            dictLevelStrVos.add(dictLevelStrVo);
        }
        return dictLevelStrVos;
    }

    @Override
    public void upChagePoi(String upId, String id) {
        // 换爹
        XyEthnic parentEthnic = getById(upId);
        XyEthnic thisEthnic = getById(id);
        String logyId = thisEthnic.getLogyId();
        thisEthnic.setParentId(upId);
        // 级别问题，如果 == 就算了，如果 大于，小于 就知道了
        if (!thisEthnic.getLevels().equals(parentEthnic.getLevels())){
            thisEthnic.setLevels(parentEthnic.getLevels() + 1);
        }
        if (thisEthnic.getLevels() < parentEthnic.getLevels()){
            thisEthnic.setLevels(parentEthnic.getLevels() - 1);
        }
        thisEthnic.setSortList(getSoftList( upId,logyId));
        updateById(thisEthnic);
    }

    @Override
    public void pleaseNewBindEthnic(String ethnicId,String user1Id) {
        String thisUserId = LoginContextHolder.me().getSysLoginUser().getStrId();
        XyUserService xyUserService = SpringUtil.getBean(XyUserService.class);
        XyLogyService xyLogyService = SpringUtil.getBean(XyLogyService.class);
        XyUser xyUser = xyUserService.getById(thisUserId);
        XyEthnic xyEthnic = getById(ethnicId);
        // 邀请人的权限是什么
        XyLogyAuth logyAuth = xyLogyAuthService.getOne(Wrappers.<XyLogyAuth>lambdaQuery().eq(XyLogyAuth::getUserId, user1Id).eq(XyLogyAuth::getLogyId, xyEthnic.getLogyId()));


//        Assert.isTrue(xyLogyAuthService.count(Wrappers.<XyLogyAuth>lambdaQuery().eq(XyLogyAuth::getUserId,thisUserId).eq(XyLogyAuth::getLogyId,xyEthnic.getLogyId()))<=0,"您已有绑定,请核实!");
        // 没有的话就 可以保存
        // 如果是 管理者 直接就是成功
        if ("*".equals(logyAuth.getPerMisc())) {
            xyEthnic.setBindFlag(NON_PRO);
            // 绑定成功后，给当前用户新增这个家谱 并且赋予权限。
            XyLogy xyLogy = xyLogyService.getById(xyEthnic.getLogyId());
            // 初始化族谱权限
            // 是否有重复
            int count = xyLogyAuthService.count(Wrappers.<XyLogyAuth>lambdaQuery().eq(XyLogyAuth::getUserId, thisUserId).eq(XyLogyAuth::getLogyId, xyLogy.getId()));
            if (count == 0)
            xyLogyAuthService.save(new XyLogyAuth(ALL_PUTONG_AUTH,thisUserId,xyUser.getPhoneNumber(),xyLogy.getId(),1));
        }else{
            xyEthnic.setBindFlag(NOT_PRO);
        }
        xyEthnic.setUserId(thisUserId);
        updateById(xyEthnic);

    }

    @Override
    public void del(String id) {
        // 是否有这个权限
        String userId = LoginContextHolder.me().getSysLoginUser().getStrId();
        XyEthnic xyEthnic = getById(id);
        XyLogyAuth logyAuth = xyLogyAuthService.getOne(Wrappers.<XyLogyAuth>lambdaQuery().eq(XyLogyAuth::getUserId, userId).eq(XyLogyAuth::getLogyId, xyEthnic.getLogyId()));
        Assert.isTrue(String.valueOf(1).equals(logyAuth.getAuth()),"权限有误,请核实!");
        // 有没有比他们 更加低的 层级，如果有的话就不能删除，
        int count = count(Wrappers.<XyEthnic>lambdaQuery().eq(XyEthnic::getLogyId, xyEthnic.getLogyId()).eq(XyEthnic::getParentId, xyEthnic.getId()).isNull(XyEthnic::getOldDataId));
        Assert.isTrue(count ==0,"您必须移除完下一代的才可以!");
        // 当前这个货有没有妻子
        int count1 = count(Wrappers.<XyEthnic>lambdaQuery().eq(XyEthnic::getLogyId, xyEthnic.getLogyId()).eq(XyEthnic::getIsJoin, xyEthnic.getId()).isNull(XyEthnic::getOldDataId));
        Assert.isTrue(count1 ==0,"请移除对应配偶!");
        removeById(id);



    }

    /**
     * 保存用户的信息
     * @param xyEthnic
     */
    private void saveAuthEthnic(XyEthnic xyEthnic) {
        XyUserService xyUserService = SpringUtil.getBean(XyUserService.class);
        XyLogyAuth logyAuth = xyLogyAuthService.getOne(Wrappers.<XyLogyAuth>lambdaQuery().eq(XyLogyAuth::getLogyId, xyEthnic.getLogyId()).eq(XyLogyAuth::getUserId, xyEthnic.getUserId()));
        if (Objects.isNull(logyAuth)){
            XyUser xyUser = xyUserService.getById(xyEthnic.getUserId());
            // 初始化
            xyLogyAuthService.save(new XyLogyAuth(ALL_PUTONG_AUTH.getAuthP(),"邀请绑定",xyUser.getId(),xyUser.getPhoneNumber(),xyEthnic.getLogyId(),1,"注册"));
        }else{
            // 修改
            logyAuth.setPerMisc(ALL_PUTONG_AUTH.getAuthP());
            xyLogyAuthService.updateById(logyAuth);
        }
    }

    /**
     * 主关系建立关系
     * @param val 全部数据
     * @param fuEthnicList 主主句
     * @return
     */
    private static List<ListEthnicVo> getListEthnicVoList(List<XyEthnic> val, List<XyEthnic> fuEthnicList) {
        return fuEthnicList.stream().map(item -> {
            ListEthnicVo listEthnicVo = new ListEthnicVo();
            BeanUtil.copyProperties(item, listEthnicVo);
            // 查找自己的对象
            listEthnicVo.setBinEthnicVos(val.stream().filter(item2 -> item.getId().equals(item2.getIsJoin())).map(item2 -> {
                ListEthnicVo listEthnicVo2 = new ListEthnicVo();
                BeanUtil.copyProperties(item2, listEthnicVo2);
                return listEthnicVo2;
            }).sorted(Comparator.comparing(ListEthnicVo::getSortList)).collect(Collectors.toList()));
            return listEthnicVo;
        }).sorted(Comparator.comparing(ListEthnicVo::getSortList)).collect(Collectors.toList());
    }

    /**
     * 通用族员查询
     * @param logyId
     * @return
     */
    private List<XyEthnic> xyEthnicList(String logyId,String formDict,Integer levels,String ...relationships){
        QueryWrapper<XyEthnic> queryWrapper = new QueryWrapper<>();

            // 根据关联的族谱编号 查询
            if (StrUtil.isNotBlank(logyId)) {
                queryWrapper.lambda().eq(XyEthnic::getLogyId,logyId);
            }

        if (StrUtil.isNotBlank(formDict)) {
            queryWrapper.lambda().like(XyEthnic::getName,formDict);
        }
        if (ObjectUtil.isNotNull(levels)) {
            queryWrapper.lambda().eq(XyEthnic::getLevels,levels);
        }

        if (ObjectUtil.isNotNull(relationships) && relationships.length >=1) {
            queryWrapper.lambda().in(XyEthnic::getRelationship,relationships);
        }
            queryWrapper.lambda().isNull(XyEthnic::getOldDataId);
            //
        return list(queryWrapper);
    }

    /**
     * 以当前等级为基点 一直延申树形结构即可
     * @param point
     * @param logyId
     */
    private TreeLogyVo doTreeChildPoint(Integer point, String logyId,String formDict,boolean isQuery) {
        TreeLogyVo treeLogyVo = new TreeLogyVo();
        List<XyEthnic> xyEthnicList = xyEthnicList(logyId,formDict,point);
        if (xyEthnicList.isEmpty()  && isQuery){
            List<XyEthnic> xyQueryEthnicList    =   xyEthnicList(logyId,null,point);
            if (xyQueryEthnicList.isEmpty()) return treeLogyVo;
        }
        if (xyEthnicList.isEmpty()  && !isQuery)return treeLogyVo;
        Integer pointLevel = point + 1;
        if (!xyEthnicList.isEmpty()){
            // 主关系确定下,先拿出来 isJoin 是null 的就是主关系
            List<XyEthnic> fuEthnicList = xyEthnicList.stream().filter(item -> StrUtil.isBlank(item.getIsJoin())).collect(Collectors.toList());
            // 这是主关系
            List<ListEthnicVo> listEthnicVos = getListEthnicVoList(xyEthnicList, fuEthnicList);
            for (ListEthnicVo listEthnicVo : listEthnicVos) {
                listEthnicVo.setChildLogyVo(doTreeChildPoint(pointLevel,logyId,formDict,isQuery));
            }
            treeLogyVo.setListEthnicVos(listEthnicVos);
        }
        return treeLogyVo;
    }


    /**
     * 以当前等级为基点 一直延申即可
     * @param point
     * @param levelsLogyVos
     * @param isQuery true 就是带参数搜素，连贯的，false 就不需要
     */
    private void doEthnicPoint(String logyId,Integer point, LinkedList<LevelsLogyVo> levelsLogyVos,String formDict,boolean isQuery) {
        // 必须是 子，女，才可以哦。
        List<XyEthnic> xyEthnicList = xyEthnicList(logyId,formDict,point,brother,father,son,daughter);
        // 这个参数判定也不行，在查一边，下面还有没有了.
        if (xyEthnicList.isEmpty() && isQuery){
            List<XyEthnic> xyQueryEthnicList    =   xyEthnicList(logyId,null,point,brother,father,son,daughter);
            if (xyQueryEthnicList.isEmpty()) return;
        }
        // 主要在这里进行断点操作
        if (xyEthnicList.isEmpty()  && !isQuery)return;
        // 排好序
        if (!xyEthnicList.isEmpty()) levelsLogyVos.addLast(new LevelsLogyVo(point,xyEthnicList.stream().sorted(Comparator.comparing(XyEthnic::getSortList)).collect(Collectors.toList())));
        Integer pointLevel = point + 1;
        doEthnicPoint(logyId,pointLevel,levelsLogyVos,formDict,isQuery);


    }

    /**
     * 权限验证相关操作
     * @param userId
     * @param ethnicEditForm
     */
    private Boolean authParms(String userId, EthnicEditForm ethnicEditForm) {

        String perMisc = getPerMisc(ethnicEditForm.getLogyId(), userId);
       // XyEthnic thisXyEthnic = getById(ethnicEditForm.getId());
        if (ALL_AUTH.getAuthP().equals(perMisc)){
            return Boolean.TRUE;
        }else{
            return Boolean.FALSE;
            // 验证
//            String[] ethnicIds = perMisc.split(",");
//            // 当前下面所有的等级下级
//            List<XyEthnic> xyEthnics = listByIds(Arrays.asList(ethnicIds));
//            for (XyEthnic xyEthnic : xyEthnics) {
//                if (xyEthnic.getLevels() > thisXyEthnic.getLevels())return Boolean.FALSE;
//            }
        }
        // throw new RuntimeException("暂无权限!");




    }

    /**
     * 进行跳转
     * @param thisEthnic
     * @param userId
     * @param ethnicForm
     */
    private void swtich(XyEthnic thisEthnic,String userId,EthnicForm ethnicForm) {
        logyLogsService.saveLogyLog(userId,ethnicForm.getLogyId(),StrUtil.format("当前族谱新增了族员,{}",ethnicForm.getName()));
        // 当前节点 需要添加什么级别的信息呢？
        // 当前的这个用户是否能操作下面的权限呢
        String relationship = ethnicForm.getRelationship();
        String parentId = thisEthnic.getParentId();
        Long genderSex = thisEthnic.getGenderSex();
        Integer levels = thisEthnic.getLevels();
        String logyId = thisEthnic.getLogyId();
        String parentIdF = thisEthnic.getId();

        if (Integer.valueOf(1).equals(levels) &&  "1".equals(parentId) && MAN_SEX.equals(genderSex) && father.equals(ethnicForm.getRelationship())){
            // 如果当前节点属于 始祖, 但是添加的是父亲，那么 整体往后回退 level+1。


            // 将自己以及往下所有级别进行降级
            // 始祖进行变更 保存当前的信息
            XyEthnic xyEthnic = commSave(ethnicForm, "1", 1L, null, 1);
            thisEthnic.setParentId(xyEthnic.getId());
            updateById(thisEthnic);
            List<XyEthnic> xyEthnics = xyEthnicMapper.selectList(Wrappers.<XyEthnic>lambdaQuery().ne(XyEthnic::getId,xyEthnic.getId()).eq(XyEthnic::getLogyId, ethnicForm.getLogyId()));
            for (XyEthnic xyEthnic1 : xyEthnics) {
                xyEthnic1.setLevels(xyEthnic1.getLevels() + 1);
            }
            updateBatchById(xyEthnics);
            return;
        }else{
            // 如果不是的话 那么就开始细分
            // 1.1 母亲 上一级
            if (mother.equals(relationship)){
                // 找到我的父 条件为 男的,等级比我高的。.eq(XyEthnic::getGenderSex, 1)
                List<XyEthnic> parentXyEthnicList = list(Wrappers.<XyEthnic>lambdaQuery().eq(XyEthnic::getLevels, thisEthnic.getLevels() - 1).eq(XyEthnic::getLogyId, thisEthnic.getLogyId()).orderByDesc(XyEthnic::getSortList));
                XyEthnic xyEthnic = parentXyEthnicList.parallelStream().filter(item -> item.getGenderSex().equals(MAN_SEX)).findAny().get();
                commSave(ethnicForm, xyEthnic.getParentId(), getSoftList(parentIdF,logyId), xyEthnic.getId(), thisEthnic.getLevels() - 1);
                return;
            }
            if (spouse.equals(relationship)){
                // 配偶
                //List<XyEthnic> parentXyEthnicList = list(Wrappers.<XyEthnic>lambdaQuery().eq(XyEthnic::getLevels, thisEthnic.getLevels()).eq(XyEthnic::getLogyId, thisEthnic.getLogyId()).orderByDesc(XyEthnic::getSortList));
                commSave(ethnicForm, thisEthnic.getParentId(), getSoftList(parentIdF,logyId), thisEthnic.getId(), thisEthnic.getLevels());
                return;
            }
            //兄妹 // 1.2 兄妹 配偶，同一级
            if (brother.equals(relationship)){
              //  List<XyEthnic> parentXyEthnicList = list(Wrappers.<XyEthnic>lambdaQuery().eq(XyEthnic::getLevels, thisEthnic.getLevels()).eq(XyEthnic::getLogyId, thisEthnic.getLogyId()).orderByDesc(XyEthnic::getSortList));
                commSave(ethnicForm, thisEthnic.getParentId(), getSoftList(parentIdF,logyId),null, thisEthnic.getLevels());
                return;
            }
           // 1.3 儿子，女儿
            if (son.equals(relationship) || daughter.equals(relationship)){
//                List<XyEthnic> childXyEthnicList = list(Wrappers.<XyEthnic>lambdaQuery().eq(XyEthnic::getLevels, thisEthnic.getLevels() - 1).eq(XyEthnic::getLogyId, thisEthnic.getLogyId()).orderByDesc(XyEthnic::getSortList));
               // 当前这个cronId 是配偶吗?
                if (spouse.equals(thisEthnic.getRelationship())){
                    commSave(ethnicForm, thisEthnic.getIsJoin(),getSoftList(parentIdF,logyId),null, thisEthnic.getLevels() + 1);
                }else{
                    commSave(ethnicForm, thisEthnic.getId(),getSoftList(parentIdF,logyId),null, thisEthnic.getLevels() + 1);

                }
            return;
            }
        }

        throw new RuntimeException("搞错了吧!");



    }

    private Long getSoftList( String parentId,String logyId) {
        List<XyEthnic> xyEthnicList = list(Wrappers.<XyEthnic>lambdaQuery().eq(XyEthnic::getLogyId,logyId).eq(XyEthnic::getParentId, parentId).orderByDesc(XyEthnic::getSortList));
        return xyEthnicList.isEmpty() ? 1L : xyEthnicList.get(0).getSortList() + 1L;
    }

    private XyEthnic commSave(EthnicForm ethnicForm,String parentId,Long sortList,String isJoin,Integer levels) {
        XyEthnic xyEthnic = new XyEthnic();
        BeanUtil.copyProperties(ethnicForm,xyEthnic);
        xyEthnic.setParentId(parentId);
        xyEthnic.setSortList(sortList);
        xyEthnic.setIsJoin(isJoin);
        xyEthnic.setLevels(levels);
        save(xyEthnic);
        return xyEthnic;

    }

    /**
     * 判定前置条件是否吻合
     * 添加，族谱细节规划流程
     * 1. 始祖。默认就是当前自己，创建完族谱后。
     * ● 始祖添加父之后，这个夫就是始祖了。
     * ● 始祖可以添加父,添加配偶，添加女儿，添加儿子。
     * 2. 配偶只可添加  儿子，女儿。往下推到 层级+1
     * 3. 儿子,女儿，只可添加 母亲，配偶，兄妹，（儿子，女儿）
     */
    private void beforeCheck( XyEthnic thisEthnic,EthnicForm ethnicForm,String userId) {
        // 当前的用户是否能操作所有的信息
//        XyLogyAuth logyAuth = xyLogyAuthService.getOne(Wrappers.<XyLogyAuth>lambdaQuery().eq(XyLogyAuth::getDisabled, 1).eq(XyLogyAuth::getLogyId, parentEthnic.getLogyId()).eq(XyLogyAuth::getUserId, userId));
//        if (!ALL_AUTH.getAuthP().equals(logyAuth.getPerMisc())){
//            // 这个用户不是所有权限,那么就开始判定是否是当前权限等级的。
//            // 将这个派系所有的id 都拿到
//            String perMisc = logyAuth.getPerMisc();
//            String[] ethnicIds = perMisc.split(",");
//            HashSet<String> ethnicSetIds = Sets.newHashSet();
//            childIds(ethnicSetIds,ethnicIds);
//            // 当前属于什么派系?
//            String id = parentEthnic.getId();
//            Assert.isTrue(ethnicSetIds.contains(id),"暂无权限编辑!");
//
//        }
        // 当前结点拿出来
        // 当前结点属于什么呢
        Integer levels = thisEthnic.getLevels();
        String parentId = thisEthnic.getParentId();
        Long genderSex = thisEthnic.getGenderSex();
        String relationship = ethnicForm.getRelationship();
        if (Integer.valueOf(1).equals(levels)){
            // 是第一世, 那么就判定 是始祖 还是配偶
            if ("1".equals(parentId) && Long.valueOf(1).equals(genderSex)){
                // 只能添加 配偶，儿女,父
                Assert.isTrue(sourceLevel.contains(relationship),"始祖只可添加 父亲,配偶,儿子,女儿!");
            }else{
                // 只能添加 儿女
                Assert.isTrue(spouseLevel.contains(relationship),"配偶只可添加儿子,女儿!");

            }
        }else{
            // 如果不是第一层,那么就是 下代的.
            // 按照顺序模板去判定
            if (relationship.equals(mother) || relationship.equals(spouse)){
                // 如果当前节点的身份是母亲|配偶，那么只能添加儿子，女儿
                Assert.isTrue(spouseLevel.contains(relationship),"配偶只可添加儿子,女儿!");
            }

            // 如果当前身份是 儿子，或者女儿 就可以添加 很多了
            if (relationship.equals(son) || relationship.equals(daughter)){
                // 如果当前节点的身份是母亲|配偶，那么只能添加儿子，女儿
                Assert.isTrue(sonLevel.contains(relationship),"不可添加父!");
            }



        }




    }

    private void childIds(HashSet<String> ethnicSetIds, String[] ethnicIds) {
    }

}
